<!-- 物料拆包 -->
<template>
  <basic-container class="production-page">
    <div style="width: 100%; display: flex">
      <div style="width: 25%; min-width: 300px; margin-right: 30px">
        <div class="bindLeft">
          <h2>物料拆包</h2>
          <avue-form ref="barCodeForm" v-model="sheetNoInfo" :option="barCodeOption" @reset-change="emptytChange" @submit="submit"> </avue-form>
        </div>
      </div>
      <div style="width: 75%; min-width: 500px">
        <h2>已拆包明细</h2>
        <avue-crud :option="option" :data="data" v-model="form" ref="crud" @row-dblclick="rowdblclickChange"> </avue-crud>
      </div>
    </div>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
  </basic-container>
</template>
<script>
import { SelectDetailPackno, UnpackingDetailSheetno } from '@/api/warehouse/materialUnpacking';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { mapGetters } from 'vuex';
import { selectInput, focusInput, ransferToNumber } from '@/util/helpers';
import { getList as getAttributeConfigList } from '@/api/system/custom-attribute-config';
export default {
  name: '',
  components: { CommonModalTemplate },
  inject: ['globalStartLoad', 'globalEndLoad'],
  data() {
    return {
      showDialog: false,
      packingList: [],
      dialogData: [],
      sheetNoInfo: {},
      barCodeOption: {
        // submitBtn: true,
        // emptyBtn: true,
        setCurrentRow: true,
        submitText: '拆包打印',
        labelWidth: 120,
        column: [
          {
            label: '包装条码',
            prop: 'sequenceNumber',
            span: 24,
            rules: [
              {
                required: true,
                message: '请扫码包装条码',
                trigger: 'submit'
              }
            ],
            enter: (value) => {
              this.packageEnter(value);
            }
          },
          {
            label: '物料编码',
            prop: 'partMasterCode',
            span: 24,
            disabled: true
          },
          {
            label: '物料名称',
            prop: 'partMasterName',
            span: 24,
            disabled: true
          },
          {
            label: '包装数量',
            prop: 'quantity',
            span: 24,
            disabled: true
          },
          {
            label: '拆出数量',
            prop: 'unpackingQuantity',
            span: 24,
            rules: [
              {
                required: true,
                message: '请输入拆出数量',
                trigger: 'submit'
              }
            ]
          },
          {
            label: '最小包装数量',
            prop: 'minPackingQuantity',
            span: 24,
            rules: [
              {
                required: true,
                message: '请输入最小包装数量',
                trigger: 'submit'
              }
            ]
          },
          {
            label: '备注',
            prop: 'remarks',
            span: 24
          },
          {
            type: 'search',
            label: '标签模板',
            prop: 'labelTemplateName',
            placeholder: '请选择 标签模板',
            span: 24,
            disabled: true,
            rules: [
              {
                required: true,
                message: '请选择模板标签',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openLabelTemplateModal();
            }
          },
          {
            label: '打印机',
            prop: 'printersName',
            type: 'search',
            placeholder: '请选择 打印机',
            disabled: true,
            span: 24,
            rules: [
              {
                required: true,
                message: '请选择打印机',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openPrintersModal();
            }
          }
        ]
      },

      data: [],
      form: {},
      query: {},
      bindLeftLoading: false,
      loading: false,
      selectionList: [],
      option: {
        height: 'calc(100vh - 289px)',
        columnBtn: false,
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        dialogClickModal: false,
        addBtn: false,
        delBtn: false,
        editBtn: false,
        viewBtn: false,
        menu: false,
        searchShow: true,
        indexLabel: '序号',
        labelWidth: 120,
        column: [
          {
            label: '包装条码',
            prop: 'sequenceNumber',
            width: 500
          },
          {
            label: '物料编码',
            prop: 'partMasterCode'
          },

          {
            label: '物料名称',
            prop: 'partMasterName'
          },
          {
            label: '包装数量',
            prop: 'quantity'
          },
          {
            label: '拆出数量',
            prop: 'unpackingQuantity',
            width: 500
          }
        ]
      },
      visibile: false,
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      finishReceive: [],
      customAttributeList: [], //扩展属性
      submitData: {}, //提交数据
      printInfo: {} //打印机打印模版信息
    };
  },
  computed: {
    ...mapGetters(['permission'])
  },
  created() {
    const fullPath = this.$route.fullPath;
    const printInfoStr = localStorage.getItem(fullPath);
    if (printInfoStr !== '{}') {
      const printInfo = JSON.parse(printInfoStr);
      const { printersName, printersId } = printInfo;
      this.sheetNoInfo.printersId = printersId;
      this.sheetNoInfo.printersName = printersName;
      this.printInfo.printersId = printersId;
    }
    const labelTemplate = localStorage.getItem('labelTemplateName');
    if (labelTemplate !== '{}') {
      const label = JSON.parse(labelTemplate);
      console.log(label, 'label');
      const { labelTemplateName, labelTemplateId } = label;
      this.sheetNoInfo.labelTemplateId = labelTemplateId;
      this.sheetNoInfo.labelTemplateName = labelTemplateName;
      this.printInfo.labelTemplateId = labelTemplateId;
    }
  },
  mounted() {
    focusInput('sequenceNumber');
  },
  methods: {
    /**
     * 打开标签模板模态框
     */
    openLabelTemplateModal() {
      this.modalName = 'labelTemplateModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择标签模版（双击进行选择）',
        url: `/api/mes-admin/labeltemplate/page?is_latest=true&type=material&subType=raw_material_packaging`,
        isPage: true,
        rowSelectionType: 'single',
        searchMenuSpan: 24,
        columnDefs: [
          {
            label: '模版名称',
            prop: 'fileName',
            search: true
          },
          {
            label: '模版代码',
            prop: 'code',
            search: true
          },
          {
            label: '客户/供应商',
            prop: 'clientName'
          },
          {
            label: '缩略图',
            prop: 'thumbnailUrl'
          },
          {
            label: '标签地址',
            prop: 'fileUrl'
          },
          {
            label: '打印列数',
            prop: 'columnCount'
          },
          {
            label: '打印份数',
            prop: 'copies'
          },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      };
    },
    /**
     * 获取打印机
     */
    openPrintersModal() {
      this.modalName = 'printersModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择打印机（双击进行选择）',
        url: '/api/mes-product/ems-equipment/page?type=PRINTER',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '打印机编码',
            prop: 'code',
            search: true,
            searchLabelWidth: 110
          },
          {
            label: '打印机名称',
            prop: 'name',
            search: true,
            searchLabelWidth: 110
          }
        ]
      };
    },
    /**
     * 获取选中打印机标签模版信息
     */
    getSelectedRows(rowData) {
      console.log(rowData, 'rowData');
      if (this.modalName === 'printersModal') {
        this.sheetNoInfo.printersName = rowData.name;
        this.printInfo.printersId = rowData.id;
        let fullPath = this.$route.fullPath;
        localStorage.setItem(
          fullPath,
          JSON.stringify({
            printersName: rowData.name,
            printersId: rowData.id
          })
        );
      } else if (this.modalName === 'labelTemplateModal') {
        this.sheetNoInfo.labelTemplateName = rowData.fileName;
        this.printInfo.labelTemplateId = rowData.id;
        let fullPath = 'labelTemplateName';
        localStorage.setItem(
          fullPath,
          JSON.stringify({
            labelTemplateName: rowData.name,
            labelTemplateId: rowData.id
          })
        );
      }
    },
    rowdblclickChange(list) {
      // this.sheetNoInfo = list;
      // this.submitData = list;
    },

    packageEnter(value) {
      let params = {
        transactionType: 'UNPACKING',
        packSeqNumList: [value]
      };
      SelectDetailPackno(params).then(
        (res) => {
          if (res.data.code == 200) {
            let data = res.data.data;
            this.packingList = data;
            this.sheetNoInfo.partMasterCode = data[0].partMasterCode ? data[0].partMasterCode : '';
            this.sheetNoInfo.partMasterName = data[0].partMasterName ? data[0].partMasterName : '';
            this.sheetNoInfo.quantity = data[0].quantity ? data[0].quantity : '';
          }
        },
        (error) => {
          this.$message({
            message: error.data.msg,
            type: 'warning'
          });
        }
      );
    },

    // 重新加载公用表格弹窗组件
    newKey() {
      this.timer = new Date().getTime();
    },
    submit(form, done) {
      console.log(form, 'form');
      this.packingList.description = form.remarks;
      let paramsMap = {
        transactionType: 'UNPACKING',
        unpackingMethod: 'QUANTITY',

        packingList: this.packingList,
        quantity: form.unpackingQuantity,
        minPackingQuantity: form.minPackingQuantity,

        equipmentId: this.printInfo.printersId,
        labelTemplateId: this.printInfo.labelTemplateId
      };
      console.log(paramsMap, 'paramsMap');
      UnpackingDetailSheetno(paramsMap).then(
        (res) => {
          if (res.data.code == 200) {
            this.$message.success(res.data.msg);
            this.data.push(this.sheetNoInfo);
            done();
          }
        },
        (error) => {
          done();
        }
      );
    },
    emptytChange() {
      this.$refs.barCodeForm.resetFields();
      this.data = [];
      this.submitData = {};
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep .el-card .is-never-shadow {
  padding: 0 !important;
}
</style>
